define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

	var Controller = {
		index  : function () {
			// 初始化表格参数配置
			Table.api.init({
				extend : {
					index_url  : 'qingdongwms/customer/quote/index',
					add_url    : 'qingdongwms/customer/quote/add',
					edit_url    : 'qingdongwms/customer/quote/edit',
					detail_url : 'qingdongwms/customer/quote/detail',
					addequipment_url : 'qingdongwms/customer/quote/add_quipment',
					table      : 'customer',
				}
			});

			var table = $("#table");

			// 初始化表格
			table.bootstrapTable({
				url          : $.fn.bootstrapTable.defaults.extend.index_url+'?createtime='+Fast.api.query("createtime"),
				pk           : 'id',
				sortName     : 'id',
				fixedColumns : true,
				fixedNumber  : 2,
				search:true,
				searchFormVisible:false,
				columns      : [
					[
						{checkbox: true},
						{
							field: 'number',
							title: '报价单编号',
							fixedColumns: true,
						 operate: "like",
							formatter: function (value, row, index) {

								return "<a href='javascript:void(0);' data-id='" + row.id + "' class='show-detail'>" + value + "</a>";
							}
						},
						{field: 'customer.name', title: '客户名称', operate: false},
						{field: 'contacts.name', title: '联系人名称', operate: false},
						{field: 'contacts.mobile', title: '联系人手机号', operate: false},
						{field: 'quote_amount', title: '报价金额'},

						{field: 'quote_date', title: '报价时间', operate: false},
						{field : 'check_status', title : '审核状态', formatter : Table.api.formatter.status,
							searchList : {0 : '待审核', 1 : '审核中', 2 : '审核通过', 3 : '审核未通过', 4 : '撤销', 5 : '草稿(未提交)',9:'作废'},operate:false},
						{field: 'status', title: '状态', formatter: Table.api.formatter.status, searchList: {0: __('进行中'), 1: __('转换成功'),9:'作废'}},
						{
							field: 'createtime',
							title: __('Createtime'),
							formatter: Table.api.formatter.datetime,
							operate: 'RANGE',
							addclass: 'datetimerange',
							sortable: true,
							width: 150
						},
						{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.buttons,
							buttons: [
								{
									name: 'edit',
									text: __('编辑'),
									title: __('编辑'),
									extend:'data-area=["90%","90%"]',
									classname: 'records btn-dialog',
									url: 'qingdongwms/customer/quote/edit',
									visible: function (row) {
										//返回true时按钮显示,返回false隐藏
										return true;
									}
								},

							]
						}
					]
				],
				onLoadSuccess:function(){
					// 这里就是数据渲染结束后的回调函数
					$(".btn-add").data("area",["90%","90%"]);
					$(".btn-edit").data("area",["90%","90%"]);
				}
			});

			$(document).on('click', '.show-detail', function (data) {
				var area = ['95%','95%'];
				var options = {
					shadeClose : false,
					shade      : [0.3, '#393D49'],
					area       : area,
					callback   : function (value) {
						//在回调函数里可以调用你的业务代码实现前端的各种逻辑和效果
						console.log(value);
					}
				};
				Fast.api.open($.fn.bootstrapTable.defaults.extend.detail_url + "?ids=" + $(this).data('id'), '报价单详情', options);
			}).on("click", ".export_pdfs",function(data){
				var ids=Table.api.selectedids(table);
				console.log(ids)
				if(ids == false){
					Layer.alert('请先选择报价单');
					return false;
				}
				if(ids.length > 10){
					Layer.alert('一次性最多下载10份报价单');
					return false;
				}
				$.each(ids,function (index,id){
					Fast.api.ajax("qingdongwms/customer/quote/download_quote?id="+id,function(data,ret){
						if(ret.code == 1){
							const aEl = document.createElement('a');
							aEl.target = '_blank';
							aEl.href = data.file;
							aEl.download = data.filename;
							aEl.click();
						}
					},function(data,ret){
					});

				})
			});

			// 为表格绑定事件
			Table.api.bindevent(table);
		},
		add    : function () {
			Controller.api.bindevent();
		},
		add_quipment    : function () {
			Controller.api.bindevent();
		},
		edit   : function () {
			Controller.api.bindevent();
		},
		detail : function () {
			Table.api.init({});
			var table = $("#table-equip");
			// 初始化表格
			table.bootstrapTable({
				url          : 'qingdongwms/customer/equipment/lists' + location.search,
				pk           : 'id',
				sortName     : 'id',
				operate      : false,
				commonSearch : false,
				search       : false,
				visible      : false,
				showColumns  : false,
				showExport   : false,
				showToggle   : false,
				columns      : [
					[
						{checkbox: true},
						{field : 'id', title : '设备ID'},
						{field : 'number', title : '设备编号'},
						{field: 'logo', title: __('二维码'), formatter: Table.api.formatter.image, events: Table.api.events.image},
						{field: 'binding_status', title: __('绑定客户产品状态'), formatter: Table.api.formatter.status, searchList: {1: __('未绑定'), 0: __('已绑定')}},
						{field: 'createtime', title: __('创建时间'), formatter: Table.api.formatter.datetime},
					]
				]
			});
			$(".btn-downloaderweima").on("click",function() {
				var temp = table.bootstrapTable('getSelections');
				var ids = temp.map(item => item.id);
				ids = ids.toString();
				if (!ids) {
					Layer.msg("请选择要下载的二维码");
					return false;
				}
				var curl = 'export_ercode?ids=' + ids;
				window.location.href = curl;
			});
			Table.api.init({});
			//附件
			var table1 = $("#files");
			table1.bootstrapTable({
				url          : 'qingdongwms/customer/quote/get_file'+ location.search,
				toolbar      : '#toolbar1',
				pk           : 'id',
				sortName     : 'id',
				operate      : false,
				commonSearch : false,
				search       : false,
				visible      : false,
				showColumns  : false,
				showExport   : false,
				showToggle   : false,
				columns      : [
					[
						{field : 'name', title : '附件名称'},
						{field : 'size', title : '附件大小'},
						{field : 'auth.username', title : '上传人'},
						{field : 'createtime', title : '上传时间',formatter: Table.api.formatter.datetime},
						{field : 'file_path', title : '文件预览', formatter : function (value, row, index) {
								return '<a href="'+value+'" class="btn btn-info" download="'+row.name+'">下载</a>';
							}},
						{
							field : 'operate', title : '操作', formatter : function (value, row, index) {
								return '<a class="btn btn-info btn-danger btn-delete-file" data-toggle="dropdown" id="" data-id="'+row.id+'">删除</a>';
							}
						},

					]
				]
			});
			Table.api.bindevent(table1);
			//操作日志
			var table2 = $("#operation_log");
			table2.bootstrapTable({
				url          : 'qingdongwms/customer/log/index?quote_id='+Config.idinfo.id,
				pk           : 'id',
				sortName     : 'id',
				toolbar      : '#toolbar2',
				operate      : false,
				commonSearch : false,
				search       : false,
				visible      : false,
				showColumns  : false,
				showExport   : false,
				showToggle   : false,
				columns      : [
					[
						{field: 'staff.name', title: __('员工')},
						{field: 'content', title: __('内容'),cellStyle:function (value,row,index,field) {
								return {
									css: {
										"min-width": "150px",
										"white-space": "nowrap",
										"text-overflow": "ellipsis",
										"overflow": "hidden",
										"max-width":"300px",
										'cursor':"pointer"
									}
								};
							},formatter:function (value,row,index,field) {
								var span=document.createElement('span');
								span.setAttribute('title',value);
								span.innerHTML = value;
								return span.outerHTML;
							}
						},
						{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},

					]
				]
			});
			// 上传
			$(document).on('click', '.btn-upload', function () {
				var id=$('#ids').val();
				Fast.api.open("qingdongwms/customer/quote/img?ids="+id, "上传",{
					shadeClose: false,
					shade: false,
					// maxmin: false,
					moveOut: false,
					scrollbars:false,
					callback:function(value){
						location.reload()
					},
				});
			});
			// 删除文件
			$(document).on('click', '.btn-delete-file', function () {
				var id=$(this).attr('data-id');
				Layer.confirm('确定删除文件吗？', {
					btn: ['确定','取消']
				},function(index, layero){
					Fast.api.ajax("qingdongwms/customer/quote/del_file?ids="+id,function(data,ret){
						if(ret.code == 1){
							location.reload();
						}
					},function(data,ret){
					});

				});
			});
			//编辑
			$(document).on('click', '.btn-edit', function () {
				var id = $('#ids').val();
				Fast.api.open("qingdongwms/customer/quote/edit?ids=" + id, "编辑报价单", {
					shadeClose : false,
					shade      : false,
					// maxmin     : false,
					moveOut    : false,
					scrollbars : false,
					area:["90%","90%"],
					callback   : function () {
						location.reload()
					}
				});

			}).on('click', ".btn-cancel", function () {//作废当前报价单
				var id = $('#ids').val();
				Layer.confirm('确定作废当前报价单吗？', {
					btn   : ['确定', '取消'],
					title : '提示',
				}, function (index, layero) {
					Fast.api.ajax("qingdongwms/customer/quote/tovoid_quote?id=" + id, function (data, ret) {
						if (ret.code == 1) {
							Layer.close(index);
							parent.location.reload();
						}
					}, function (data, ret) {
					});

				});
			}).on("click", "#download",function(res){
				var id = $('#ids').val();
				Fast.api.ajax("qingdongwms/customer/quote/download_quote?id="+id,function(data,ret){

					 if(ret.code == 1){
						 const aEl = document.createElement('a');
						 aEl.target = '_blank';
						 aEl.href = data.file;
						 aEl.download = data.filename;
						 aEl.click();
					 }
				},function(data,ret){
				});
			}).on('click','.btn-contract',function () {
				var id=$('#ids').val();
				Fast.api.open("qingdongwms/customer/contract/quote_change?quote_id="+id, "转为合同",{
					shadeClose: false,
					shade: false,
					maxmin: false,
					moveOut: false,
					scrollbars:false,
					area:["90%","90%"],
					callback:function(value){
					},
				});

			});

			$('.btn-ajax').data("success", function(data, ret){
				//处理回调
				location.reload();
			})
			Controller.api.bindevent();
		},
		set_team    : function () {
			$(document).on('click','.btn-zhidu',function () {
				$(this).parent().parent().find('.is_edit').html('只读')
				$(this).parent().parent().find('.staff_is_edit').val(0)
				$(this).parent().find('.btn-duxie').show()
				$(this).hide()
				layer.msg('权限更改为只读')
			})
			$(document).on('click','.btn-duxie',function () {
				$(this).parent().parent().find('.is_edit').html('读写')
				$(this).parent().parent().find('.staff_is_edit').val(1)
				$(this).parent().find('.btn-zhidu').show()
				$(this).hide()
				layer.msg('权限更改为读写')
			})
			$(document).on('click','.btn-delone',function () {
				$(this).parent().parent().remove()
			});

			Controller.api.bindevent();
		},

		add_team    : function () {
			Form.api.bindevent($("form[role=form]"), function(data, ret){
				//这里是表单提交处理成功后的回调函数，接收来自php的返回数据
				Fast.api.close(data);//这里是重点
			});
		},
		img    : function () {
			Controller.api.bindevent();
			$("#plupload-avatar").data("upload-success", function(res){
				res.id;
				var imgs = $('#hidden-img').val();
				if(imgs){
					imgs +=','+res.id;
				}else{
					imgs = res.id;
				}
				$('#hidden-img').val(imgs);
			});

		},
		api    : {
			bindevent : function () {
				function setQuoteAmount(){
					var number=$('.fieldlist').find('.number');
					var price=0;
					$.each(number,function (index,data){
						var price_unit=$('.price').eq(index).val(),num=$(data).val();
						price_unit=parseInt(price_unit)
						num=parseInt(num)
						if(price_unit && num){
							price+=price_unit*num;
						}
					})
					var discount_money=$('#c-discount_money').val();
					discount_money=parseInt(discount_money)
					price=price-discount_money;
					price=parseInt(price)
					$('#c-quote_amount').val(price)
				}
				$(document).on("fa.event.appendfieldlist", '.fieldlist', function(){
					//通用的表单组件事件绑定和组件渲染
					Form.events.selectpage($("form"));
					$(".fieldlist .price").trigger("change");
				});
				$("#c-contacts").data("params", function (obj) {
					var customer_id=$('#c-customer_id').val();
					return {customer_id: customer_id};
				});

				$(document).on("change", ".product", function () {
					var $this = $(this);
					var id = $this.next('input').val();
					Fast.api.ajax("qingdongwms/common/getProductPrice?id=" + id, function (data, ret) {
						$this.parent().parent().next('span').find('input').val(data.price);
						$this.parent().parent().next('span').next('span').find('input').val(1);
						$(".fieldlist .price").trigger("change");
						return false;
					});
				}).on("change", "#c-is_check", function () {
					if ($(this).val() == 1) {
						$('#c-flow_staff_ids').show();
					} else {
						$('#c-flow_staff_ids').hide();
					}
				}).on('change', '.price', function () {
					setQuoteAmount();
				}).on('change', '.number', function () {
					setQuoteAmount();
				}).on('change', '#c-discount_money', function () {
					setQuoteAmount();
				}).on("click", ".select-customer", function(){
					var $this=$(this);
					top.Fast.api.open($(this).data("url") , __('Select'), {callback: function (data) {
							$this.html(data.name);
							$('[name="'+$this.data('name')+'"]').val(data.id);
						},area:["100%", "100%"]});
				}).on("click", ".select-contacts", function(){
					var $this=$(this),customer_id=$('[name="row[customer_id]"]').val();
					if(!customer_id){
						Layer.msg('请先选择客户');
						return false;
					}
					top.Fast.api.open($(this).data("url")+"&customer_id="+customer_id , __('Select'), {callback: function (data) {
							$this.html(data.name);
							$('[name="'+$this.data('name')+'"]').val(data.id);
						},area:["100%", "100%"]});
				}).on("click", ".select-product", function(){
					var $this=$(this);
					top.Fast.api.open($(this).data("url"), __('Select'), {callback: function (data) {
							$this.html(data.name);
							$('[name="'+$this.data('name')+'"]').val(data.id);
							$this.parent().parent().next('td').find('input').val(data.price);

							setQuoteAmount();
							$(".fieldlist input:eq(2)").trigger("change");
						},area:["100%", "100%"]});
				});
				Form.api.bindevent($("form[role=form]"), function (data, ret) {
					//这里是表单提交处理成功后的回调函数，接收来自php的返回数据

					Fast.api.close(data);//这里是重点
					window.location.reload();
				}, function (data, ret) {
					Toastr.error(ret.msg);
					return false;
				});
			}
		}
	};
	return Controller;
});